package com.cskaoyan.order.biz.handler;

import com.cskaoyan.mall.commons.exception.BizException;
import com.cskaoyan.mall.dto.ClearCartItemRequest;
import com.cskaoyan.mall.order.constant.OrderRetCode;
import com.cskaoyan.order.api.ProductApi;
import com.cskaoyan.order.biz.context.CreateOrderContext;
import com.cskaoyan.order.biz.context.TransHandlerContext;
import com.cskaoyan.order.dto.CartProductDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.LinkedList;
import java.util.List;


@Slf4j
@Component
public class ClearCartItemHandler extends AbstractTransHandler {

    // 删除购物车商品，调用商品服务
    @Autowired
    ProductApi productApi;


    //是否采用异步方式执行
    @Override
    public boolean isAsync() {
        return false;
    }

    @Override
    public boolean handle(TransHandlerContext context) {
        try{
            CreateOrderContext createOrderContext = (CreateOrderContext) context;
            Long userId = createOrderContext.getUserId();
            ClearCartItemRequest clearCartItemRequest = new ClearCartItemRequest();
            List<CartProductDto> cartProductDtoList = createOrderContext.getCartProductDtoList();
            LinkedList<Long> productIds = new LinkedList<>();
            for (CartProductDto cartProductDto : cartProductDtoList) {
                productIds.add(cartProductDto.getProductId());
            }

            clearCartItemRequest.setProductIds(productIds);
            clearCartItemRequest.setUserId(new Long(createOrderContext.getUserId()));
            productApi.clearCartItemByUserID(clearCartItemRequest);
        }catch (Exception e){
            throw new BizException(OrderRetCode.DB_SAVE_EXCEPTION.getCode(),OrderRetCode.DB_SAVE_EXCEPTION.getMessage());
        }

        return true;
    }
}
